package com.zr.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zr.datamodel.FuncDM;
import com.zr.datamodel.UserDM;
import com.zr.service.FuncService;
import com.zr.service.UserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@Scope(value = "prototype") // 以多例的方式生成
public class UserAction {

	@Resource
	private UserService userService;

	@Resource
	private FuncService funcService;

	private UserDM user;

	public UserDM getUser() {
		return user;
	}

	public void setUser(UserDM user) {
		this.user = user;
	}

	public String login() {
		try {
			UserDM currentUser = userService.findUserByAccountAndPassword(user);
			if (currentUser == null) {
				return "error";
			}
			HttpServletRequest req = ServletActionContext.getRequest();
			HttpSession session = req.getSession();
			session.setAttribute("CURRENT_USER", currentUser);
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success";

	}

	/**
	 * 加载功能列表
	 */
	public void loadMenu() {
		try {
			HttpServletResponse resp = ServletActionContext.getResponse();
			resp.setCharacterEncoding("utf-8");
			HttpServletRequest req = ServletActionContext.getRequest();
			HttpSession session = req.getSession();
			UserDM currentUser = (UserDM) session.getAttribute("CURRENT_USER");
			JSONArray jsonArray = new JSONArray();
			List<FuncDM> parentFuncs = funcService.findFuncsByRoleId(currentUser.getRole().getId());
			for (FuncDM parentFunc : parentFuncs) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", parentFunc.getId());
				jsonObject.put("text", parentFunc.getName());
				jsonObject.put("state", "close");
				jsonObject.put("children", funcService.queryAllFunc(parentFunc.getId()));
				jsonArray.add(jsonObject);
			}
			PrintWriter writer = resp.getWriter();
			writer.write(jsonArray.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
